<template>
  <div class="home-view-page">
    <div style="height: 300px; width: 100%">
      <a-carousel arrows autoplay>
        <template #prevArrow>
          <div class="custom-slick-arrow" style="left: 10px; z-index: 1">
            <left-circle-outlined />
          </div>
        </template>
        <template #nextArrow>
          <div class="custom-slick-arrow" style="right: 10px">
            <right-circle-outlined />
          </div>
        </template>
        <div>
          <h3>1</h3>
        </div>
        <div>
          <h3>2</h3>
        </div>
        <div>
          <h3>3</h3>
        </div>
        <div>
          <h3>4</h3>
        </div>
      </a-carousel>
    </div>
    <div class="home-content">
      <div class="title">热门课程</div>
      <a-row :gutter="[12, 12]">
        <a-col :xs="24" :sm="12" :md="8" :xl="8" :xxl="8" v-for="item in cardList" :key="item.id">
          <a-card hoverable class="home-card-item" @click="handleShowCourseDetail(item)">
            <template #cover>
              <img
                alt="example"
                :src="'https://editor-img.888ban.com/gif_complete_img/2021-06-03/small_7aff96ffa4caef23f972208f19eeba23.png?auth_key=2285856000-0-0-c3ee70b4da1035bd15598878ebb42e7d'"
                style="width: 100%; height: 200px; position: relative"
              />
              <a-button
                type="primary"
                shape="circle"
                v-if="isShowAddButton(item)"
                style="position: absolute; right: 15px; bottom: 120px; width: 40px; height: 40px"
                @click.stop="handleAddCourse(item)"
              >
                <plus-outlined style="font-size: 20px; font-weight: bold; line-height: 36px" />
              </a-button>
            </template>
            <a-card-meta :title="item.title">
              <template #description>{{ item.description }}</template>
            </a-card-meta>
            <div class="card-bottom flex-between">
              <div>
                {{ item.teachername }}
              </div>
              <div style="cursor: pointer" @click.stop="handleAddAttention(item)">
                {{ getAttentionStatus(item) }}
              </div>
              <div>
                <UserOutlined />
                {{ item.curriculavariablecount }}
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <template v-if="!getToken()">
      <a-tooltip>
        <template #title>未登录</template>
        <div class="float-button" style="bottom: 120px; background: #cccccc" @click="() => handleOpenSyatem('index')">
          <UserOutlined style="color: #ffffff; font-size: 18px" />
        </div>
      </a-tooltip>
    </template>
    <template v-else>
      <Dropdown placement="topRight">
        <div class="float-button" style="bottom: 120px">
          <UserOutlined style="color: #ffffff; font-size: 18px" />
        </div>
        <template #overlay>
          <a-menu style="width: 100px">
            <a-menu-item>
              <a href="javascript:;" @click="() => handleOpenSyatem('system/usersetting')">个人中心</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="() => handleOpenSyatem('myCourseManagement/MyCourseManagementList')">我的课程</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="() => handleOpenSyatem('myAttention/MyAttentionList')">关注课程</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="handleOpenFeedbackModal">反馈投诉</a>
            </a-menu-item>
          </a-menu>
        </template>
      </Dropdown>
    </template>

    <div class="float-button" @click="handleOpenService">
      <CustomerServiceOutlined style="color: #ffffff; font-size: 18px" />
    </div>

    <ServicePopover v-model:modalVisible="openServiceModal" ref="servicePopoverRef" @sendMessage="onSendMessage" />

    <!-- <CourseDetailModal v-model:modelValue="openCourseDetailModal" :courseDetail="courseDetail" :myCourseList="myCourseList" /> -->

    <ComplaintsFeedbackModal ref="complaintsFeedbackModalRef" />
  </div>
</template>

<script lang="ts" setup>
  import { onBeforeUnmount, onMounted, ref } from 'vue';
  import { LeftCircleOutlined, RightCircleOutlined, CustomerServiceOutlined, UserOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import ServicePopover from './components/ServicePopover.vue';
  import { getLoginBackInfo, getToken } from '/@/utils/auth';
  import CourseDetailModal from './components/CourseDetailModal.vue';
  import { Dropdown, message } from 'ant-design-vue';
  import WebSocketClass from '../../utils/websocket';
  import { router } from '/@/router';
  import { useGlobSetting } from '/@/hooks/setting';
  import { Modal } from 'ant-design-vue';
  import { getMyCourseList, saveOrUpdate } from '../myCourseManagement/MyCourseManagement.api';
  import { list } from '../courseManagement/CourseManagement.api';
  import { myAttentionList, saveAttention, deleteAttention } from '../myAttention/MyAttention.api';
  import { getDeviceId } from '/@/utils/util';
  import { PageEnum } from '/@/enums/pageEnum';
  import { formatToDateTime } from '/@/utils/dateUtil';
  import ComplaintsFeedbackModal from '../complaintsFeedback/components/ComplaintsFeedbackModal.vue';
  import { getUserInfo } from '/@/api/sys/user';
  import { useUserStore } from '/@/store/modules/user';

  const cardList = ref([]);
  const myCourseList = ref([]);

  const openServiceModal = ref(false);

  const serviceId = 'e9ca23d68d884d4ebb19d07889727dae';

  const websocketInstance = ref<WebSocketClass | null>(null);
  const isWebSocketConnected = ref(false);
  const glob = useGlobSetting();

  const complaintsFeedbackModalRef = ref();

  // const openCourseDetailModal = ref(false);

  const courseDetail = ref();

  const servicePopoverRef = ref();
  const attentionList = ref([]);

  const handleOpenService = () => {
    openServiceModal.value = true;
  };

  const handleOpenSyatem = (url) => {
    if (url == 'index') {
      router.replace({ path: PageEnum.BASE_LOGIN, query: { redirect: url } });
      return;
    }
    window.open(url, '_blank');
  };

  const loadData = async () => {
    const params = {
      column: 'createTime',
      order: 'desc',
      pageNo: 1,
      pageSize: 100,
    };
    const res = await list(params);
    cardList.value = res.records || [];
  };

  const onSendMessage = async (value) => {
    if (value.length == 0 || value.trim().length == 0) {
      return;
    }
    websocketInstance.value.sendMsg(
      JSON.stringify({
        type: 'user_chat',
        deviceId: getDeviceId(),
        data: {
          content: value,
          createTime: new Date().getTime(),
          senderId: getDeviceId(),
          receiverId: serviceId,
        },
      })
    );
  };

  const handleOpenFeedbackModal = () => {
    if (!complaintsFeedbackModalRef.value) {
      return;
    }
    complaintsFeedbackModalRef.value.disableSubmit = false;
    complaintsFeedbackModalRef.value.add();
  };

  const getAttentionStatus = (item) => {
    if (!getToken()) {
      return '关注';
    }
    const index = attentionList.value.findIndex((children) => children.courseId == item.id);
    if (index == -1) {
      return '关注';
    }
    return '已关注';
  };

  const isShowAddButton = (item) => {
    console.log('isShowAddButton  item ==>', item);
    return myCourseList.value.findIndex((child) => child.courseId == item.id) == -1;
  };

  const closeWebSocket = () => {
    if (websocketInstance.value) {
      websocketInstance.value.closeSocket('关闭连接');
      console.log('WebSocket 已关闭');
    }
  };

  const handleShowCourseDetail = (item) => {
    courseDetail.value = item;
    // setTimeout(() => {
    // openCourseDetailModal.value = true;
    // router.replace({ path: PageEnum.INDEX_DETAIL, query: { id: item.id } });
    window.open(PageEnum.INDEX_DETAIL + '?id=' + item.id, '_blank');
    // }, 200);
  };

  const handleAddAttention = async (item) => {
    if (getAttentionStatus(item) == '关注') {
      const params = {
        courseId: item.id,
        courseName: item.title,
        createTime: formatToDateTime(new Date()),
      };
      await saveAttention(params, false);
      await loadAttentionData();
      return;
    }
    const list = attentionList.value.filter((child) => child.courseId == item.id);
    if (list.length == 0) {
      return;
    }
    attentionList.value = attentionList.value.filter((child) => child.courseId != item.id);

    await deleteAttention({ id: item.id });
  };

  onBeforeUnmount(() => {
    closeWebSocket();
  });

  const initWebSocket = () => {
    websocketInstance.value = new WebSocketClass({});
    isWebSocketConnected.value = websocketInstance.value.isConnect.value;

    websocketInstance.value.setMessageCallback((msg) => {
      console.log('外部收到消息 22222:', msg);
      if (!msg) {
        return;
      }
      const newData = JSON.parse(msg);
      if (newData.type == 'heart_beat') {
        return;
      }
      if (!servicePopoverRef.value) {
        return;
      }
      servicePopoverRef.value.getMessageInfo({
        deviceId: getDeviceId(),
        content: newData.content,
        id: newData.id,
        senderId: serviceId,
        receiverId: getDeviceId(),
      });
    });
  };

  const userStore = useUserStore();
  const handleAddCourse = (item) => {
    if (!getToken()) {
      return;
    }
    // console.log('getLoginBackInfo  ==>', userStore.getUserInfo)
    Modal.confirm({
      title: '确定选择该课程吗?',
      content: '选择课程后不能取消，请谨慎选择',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        const params = {
          ...item,
          createBy: userStore.getUserInfo.username,
          updateBy: userStore.getUserInfo.username,
          courseId: item.id,
        };
        delete params.id;
        const res = await saveOrUpdate(params, false);
        console.log('index 添加课程 res ==>', res);
        message.success('添加成功');
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const loadAttentionData = async () => {
    const params = {
      column: 'createTime',
      order: 'desc',
      pageNo: 1,
      pageSize: 100,
    };
    const res = await myAttentionList(params);

    attentionList.value = res.records || [];
  };

  const loadMyCourseData = async () => {
    const params = {
      column: 'createTime',
      order: 'desc',
      pageNo: 1,
      pageSize: 100,
    };
    const res = await getMyCourseList(params);
    console.log('loadMyCourseData res 12323 ==>', res);
    myCourseList.value = res.records || [];
  };

  onMounted(() => {
    initWebSocket();

    loadData();
    if (!getToken()) {
      return;
    }
    loadAttentionData();
    loadMyCourseData();
  });
</script>

<style lang="less" scoped>
  .home-view-page {
    width: 100vw;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-direction: column;

    .title {
      font-size: 26px;
      padding: 15px 0;
    }

    .home-content {
      max-width: 1000px;
      margin: 30px 20px;

      .card-bottom {
        margin-top: 20px;
      }
    }

    .flex-between {
      display: flex;
      justify-content: space-between;
    }

    .float-button {
      position: fixed;
      right: 60px;
      bottom: 60px;
      border-radius: 50%;
      width: 40px;
      height: 40px;
      background: deepskyblue;
      line-height: 40px;
      text-align: center;
      cursor: pointer;
    }

    :deep(.slick-slide) {
      text-align: center;
      height: 300px;
      line-height: 300px;
      background: #364d79;
      overflow: hidden;
    }

    :deep(.slick-arrow.custom-slick-arrow) {
      width: 25px;
      height: 25px;
      font-size: 25px;
      color: #fff;
      background-color: rgba(31, 45, 61, 0.11);
      transition: ease all 0.3s;
      opacity: 0.3;
      z-index: 1;
    }

    :deep(.slick-arrow.custom-slick-arrow:before) {
      display: none;
    }

    :deep(.slick-arrow.custom-slick-arrow:hover) {
      color: #fff;
      opacity: 0.5;
    }

    :deep(.slick-slide h3) {
      color: #fff;
    }
  }
</style>
